package com.freeter.modules.cityrecord.service.impl;

import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.freeter.common.provincecity.ProvinceCityCache;
import com.freeter.common.utils.PageInfo;
import com.freeter.common.utils.PageUtils;
import com.freeter.modules.cityrecord.dao.CityRecordDao;
import com.freeter.modules.cityrecord.entity.CityRecordEntity;
import com.freeter.modules.cityrecord.entity.view.CityHotMapView;
import com.freeter.modules.cityrecord.entity.view.CityRecordView;
import com.freeter.modules.cityrecord.entity.vo.CityRecordVO;
import com.freeter.modules.cityrecord.service.CityRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@SuppressWarnings({"unchecked", "rawtypes"})
@Service("cityRecordService")
public class CityRecordServiceImpl extends ServiceImpl<CityRecordDao, CityRecordEntity> implements CityRecordService {
    @Autowired
    private CityRecordDao cityRecordDao;

    @Override
    public PageUtils queryPage(PageInfo pageInfo, Wrapper<CityRecordEntity> wrapper) {
        Page<CityRecordView> page = pageInfo.getPage();
        page.setRecords(baseMapper.selectListView(page, wrapper));
        page.getRecords().forEach(vo -> setProvinceCityName(vo));
        PageUtils pageUtil = new PageUtils(page);
        return pageUtil;

    }

    @Override
    public List<CityRecordVO> selectListVO(Wrapper<CityRecordEntity> wrapper) {
        return baseMapper.selectListVO(wrapper);
    }

    @Override
    public CityRecordVO selectVO(Wrapper<CityRecordEntity> wrapper) {
        return baseMapper.selectVO(wrapper);
    }

    @Override
    public List<CityRecordView> selectListView(Wrapper<CityRecordEntity> wrapper) {
        return baseMapper.selectListView(wrapper);
    }

    @Override
    public CityRecordView selectView(Wrapper<CityRecordEntity> wrapper) {
        return baseMapper.selectView(wrapper);
    }

    private void setProvinceCityName(Object obj) {
        if (obj instanceof CityRecordVO) {
        } else if (obj instanceof CityRecordEntity) {
            CityRecordEntity cityRecordEntity = (CityRecordEntity) obj;
            cityRecordEntity.setProvinceName(ProvinceCityCache.getProvince(cityRecordEntity.getProvinceId()).getProvince());
            cityRecordEntity.setCityName(ProvinceCityCache.getCity(cityRecordEntity.getCityId()).getCity());
        }

    }

    @Override
    public List<CityHotMapView> selectHotCityMap() {
        return cityRecordDao.selectHotCity();
    }

    /**
     * 根据省份名字获取记录
     *
     * @param provinceName
     * @return
     */
    @Override
    public List<CityRecordEntity> selectRecordByProvince(String provinceName) {
        return cityRecordDao.selectRecordByProvince(provinceName);
    }
}
